package com.itheima.interceptor;


import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// 自定义拦截器
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    // 重写preHandle方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle...");

        String requestURL = request.getRequestURL().toString();
        log.info("请求的url:{}", requestURL);

        if (requestURL.contains("login")) {
            log.info("放行登录请求");
            return true;
        }

        String token = request.getHeader("token");
        if(!StringUtils.hasLength(token)){
            log.info("请求头token为空");
            Result error = Result.error("not_login");
            String jsonString = JSONObject.toJSONString(error);
            response.getWriter().write(jsonString);
            return false;
        }
        try {
            JwtUtils.parseJWT(token);
        }catch (Exception e){
            log.info("token解析失败");
            Result error = Result.error("not_login");
            String jsonString = JSONObject.toJSONString(error);
            response.getWriter().write(jsonString);
            return false;
        }

        log.info("token验证通过");
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle...");
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion...");
    }
}
